<?php

class Application_Model_Mapper_LogbuchMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Logbuch');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Logbuch $logbucheintrag)
	{		
		
		
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
		
			$data = array(
					'id' => $generatedid,
					'turn' => $logbucheintrag->getTurn(),
					'created' => date('Y-m-d H:i:s'),
					'erstellerid' => $logbucheintrag->getErstellerid(),
					'titel' => $logbucheintrag->getTitel(),
					'inhalt' => $logbucheintrag->getInhalt(),
					'papierkorb' => 0
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($logbucheintrag);
		}
		
	}
	
	
	public function delete($id)
	{
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $id);
		$table->delete($where);
	}


	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('logbuch');
		$entry->where('logbuch.id = ?', $id);
		return $entry->query()->fetch();
	}


	public function fetchTurn($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('logbuch', array('created AS created_logbuch','*'));
		$entry->where('logbuch.turn = ?', $id);
		$entry->joinleft(
				array('users' => 'users'),
				'logbuch.erstellerid = users.id');
		$entry->order('created_logbuch DESC');
		return $entry->query()->fetchall();
	}
	public function fetchErsteller($id)
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
		$entry->from('logbuch');
		$entry->where('logbuch.ersteller = ?', $id);
		return $entry->query()->fetchall();
	}
	
}




